﻿using BestTrader.Cms.Core;
using BestTrader.Cms.Core.Helper;
using BestTrader.Cms.Models;
using BestTrader.Cms.ViewModels;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BestTrader.Cms.Admin.Filter
{
    public class GlobalAccountFilter : Attribute, IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext context)
        {

        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            var path = context.HttpContext.Request.Path;
            var res = context.HttpContext.AuthenticateAsync().Result;
            if (res.None)
            {
                context.Result = new RedirectResult($"/Account?returnUrl={path}");
            }
            if (res.Succeeded)
            {
                var ctrl = context.Controller as ControllerBase;
                if (ctrl != null)
                {
                    var _user = ctrl.User.Claims.FirstOrDefault();
                    if (_user == null)
                    {
                        context.Result = new RedirectResult($"/Account?returnUrl={path}");
                    }
                }
                
            }
        }
    }
}
